package com.cgwx.tcservice.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

/**
 * @author GaoWei
 * @Date 2023/9/22 - 11:48
 */

@Service
public class NettyUdpSendServer {
    public void send(String message, String sendingIP, int sendingPort) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap  = new Bootstrap();
            bootstrap.group(group)
                     .channel(NioDatagramChannel.class)
                     .option(ChannelOption.SO_BROADCAST, true)
                     .handler(new ChannelInitializer<>() {
                         @Override
                         protected void initChannel(Channel ch) {
                            // 不需要任何处理
                         }
                     });
            Channel channel = bootstrap.bind(1234).sync().channel();
//            对方以16进制接收
            byte[] bytes = new byte[message.length() / 2];
            for (int i = 0; i < message.length(); i += 2) {
                bytes[i / 2] = (byte) ((Character.digit(message.charAt(i), 16) << 4) + Character.digit(message.charAt(i+1), 16));
            }
//            分配指定大小的ByteBuf
            ByteBuf byteBuf = channel.alloc().buffer(message.length() / 2);
//            将十六进制字符串写入ByteBuf
            byteBuf.writeBytes(bytes);
            DatagramPacket packet = new DatagramPacket(byteBuf, new InetSocketAddress(sendingIP, sendingPort));
//            发送数据包，不会阻塞当前线程，发送完成会回调handler中的方法。
            channel.writeAndFlush(packet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
